package com.GraduationDesign.backend.blImpl.project;

import com.GraduationDesign.backend.bl.git.GitService;
import com.GraduationDesign.backend.bl.project.ProjectService;
import com.GraduationDesign.backend.data.project.ProjectMapper;
import com.GraduationDesign.backend.data.user.AccountMapper;
import com.GraduationDesign.backend.enums.FileType;
import com.GraduationDesign.backend.enums.UserType;
import com.GraduationDesign.backend.po.*;
import com.GraduationDesign.backend.utils.RequestUtil;
import com.GraduationDesign.backend.vo.GithubUrl;
import com.GraduationDesign.backend.vo.ProjectVO;
import com.GraduationDesign.backend.vo.ResponseVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: wzx
 * @date: 2022/4/1
 */
@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    AccountMapper accountMapper;
    @Autowired
    GitService gitService;
    @Autowired
    RestTemplate restTemplate;

    private final static String PRLIST_URL ="http://172.31.105.39:8000/api/diff/getPRList";

    @Override
    public ResponseVO addProject(ProjectVO projectVO) {
        Project project=new Project();
        BeanUtils.copyProperties(projectVO,project);
        GitInfo gitInfo=new GitInfo();
        gitInfo.setOwner(project.getRepositoryOwner());
        gitInfo.setRepo(project.getRepositoryName());
        gitService.clone(gitInfo);
        projectMapper.addProject(project);
        return ResponseVO.buildSuccess("成功添加项目");
    }

    @Override
    public ResponseVO deleteProject(int projectId) {
        if(projectMapper.getProject(projectId)){
        projectMapper.deleteProject(projectId);
        return ResponseVO.buildSuccess("成功删除项目"+projectId);}
        else{
            return ResponseVO.buildFailure("项目不存在");
        }
    }

    @Override
    public List<Project> getProjects(int userId) {
        UserType type= accountMapper.getUserType(userId);
        if(type==UserType.Coder){
            return projectMapper.getProjects(userId);
        }
        else if(type==UserType.Reviewer){
            return projectMapper.getAllProjects();
        }
        return null;
    }
    @Override
    public List<PullRequest> getPrList(Integer programId) {
        String url=projectMapper.getProjectAddress(programId);
        return JSONArray.parseArray(getPort(url).getData(),PullRequest.class);
    }
    @Override
    public PrResponse getPort(String url) {
        GithubUrl githubUrl=new GithubUrl(url);
        HttpEntity<GithubUrl> httpEntity=new HttpEntity<>(githubUrl);
        ResponseEntity<String> responseEntity=null;
        PrResponse prResponse=null;
        try {
            responseEntity = RequestUtil.getPRList(PRLIST_URL, url);
            JSONObject jsonObject=JSONObject.parseObject(responseEntity.getBody());
            prResponse= JSON.parseObject(String.valueOf(jsonObject),PrResponse.class);
            log.info(String.valueOf(responseEntity));
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return prResponse;
    }
    @Override
    public GithubFile FileTree(String path) {
        GithubFile githubFile=new GithubFile();
        File file=new File(path);
        githubFile.setTitle(file.getName());
        githubFile.setKey(file.getAbsolutePath());
        File[] files=file.listFiles();
        if(!file.exists()){
            log.info("文件不存在");
            return null;
        }
        if(files==null){
            githubFile.setSlots(new Slots(FileType.file));
            githubFile.setChildren(null);
            return githubFile;
        }
        githubFile.setSlots(new Slots(FileType.folder));
        githubFile.setChildren(new ArrayList<GithubFile>());
        for(File f:files){
            githubFile.getChildren().add(FileTree(f.getAbsolutePath()));
        }
        return githubFile;
    }

    @Override
    public String getFile(String path) {
        File file=new File(path);
        StringBuilder result= new StringBuilder();
        if(!file.exists()){
            log.info("文件不存在");
            return null;
        }
        if(file.isDirectory()){
            log.info("该文件为文件夹");
            return null;
        }
        BufferedReader reader = null;
        try {
//            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                result.append(tempString);
                result.append("\n");
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return result.toString();
    }




}
